﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using WeChartWorkRobot.Common;
using WeChartWorkRobot.Model;
using WeChartWorkRobot.Service;
using WeChartWorkRobot.Service.Jobs;

namespace WeChartWorkRobot
{
    internal static class AppRuntime
    {

        public static void Initialize()
        {
            InitLogSystem();
            InitFile();
            InitJobs();
            LogHelper.Debug("机器人初始化完成");
        }

        /// <summary>
        /// 初始化定时任务
        /// </summary>
        private static void InitJobs()
        {
            // 支持两种触发模式：

            // 1、cron表达式：CronTrigger
            // 每分钟运行1次          0 * * * * ? 
            // 每30分钟运行1次      0 0/30 * * * ? 
            // 每小时运行1次          0 0 * * * ? 
            // 每天0点运行             0 0 0 * * ? 

            // 示例：
            // JobManager.AddJob<YourJobClass>(new CronTrigger("0 * * * * ?"));

            // 2、简单定时触发：SimpleTrigger
            // intevalSecond: 触发频率（秒）
            // repeat: 重复次数（-1为不限）

            // 示例：（每分钟触发一次，次数不限）
            // new SimpleTrigger(60, -1);

            // --------------------------

            // 先初始化任务管理器
            JobManager.Initialize();


            List<WxMsg> wxMsgs = XmlHelper.XmlDeserializeFromFile<List<WxMsg>>(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, ConstService.APP_DATA_PATH, ConstService.NOMAL_TEXT_MSG_PATH));

            foreach (WxMsg wxMsg in wxMsgs)
            {
                Dictionary<string, object> dataDic = new Dictionary<string, object>();
                dataDic["wxMsg"] = wxMsg;
                if (wxMsg.interval_type == 1)
                {
                    JobManager.AddJob<SendMsgJob>(new SimpleTrigger(Convert.ToInt32(wxMsg.interval), wxMsg.repeat), dataDic);
                }
                else
                {
                    JobManager.AddJob<SendMsgJob>(new CronTrigger(wxMsg.interval), dataDic);
                }
            }


            List<CustomerWxMsg> customerWxMsgs = XmlHelper.XmlDeserializeFromFile<List<CustomerWxMsg>>(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, ConstService.APP_DATA_PATH, ConstService.CST_TEXT_MSG_PATH));

            foreach (CustomerWxMsg wxMsg in customerWxMsgs)
            {
                Dictionary<string, object> dataDic = new Dictionary<string, object>();
                dataDic["wxMsg"] = wxMsg;
                if (wxMsg.interval_type == 1)
                {
                    JobManager.AddJob<SendCustomerMsgJob>(new SimpleTrigger(Convert.ToInt32(wxMsg.interval), wxMsg.repeat), dataDic);
                }
                else
                {
                    JobManager.AddJob<SendCustomerMsgJob>(new CronTrigger(wxMsg.interval), dataDic);
                }
            }

            /*
            //每周五早上8点
            JobManager.AddJob<TaskRemind>(new CronTrigger("0 0 8 ? * FRI"));
            //每个工作日下午16:30点提醒订餐
            JobManager.AddJob<MeiCan>(new CronTrigger("0 30 16 ? * MON-FRI"));
            //每周粉丝群提醒
            JobManager.AddJob<HighDataGroupRemind>(new CronTrigger("0 0 10 ? * Wed"));

            //每天早上8点提醒JIRA反馈情况(周一到周四)
            JobManager.AddJob<HighDataFeedBackByEveryDay>(new CronTrigger("0 0 8 ? * MON-THU"));

            //每天下午17点提醒JIRA反馈情况(周一到周四)
            JobManager.AddJob<HighDataFeedBackByEveryDay>(new CronTrigger("0 0 17 ? * MON-THU"));

            //每天早上8点提醒JIRA反馈情况(周五提醒本周汇总信息)
            JobManager.AddJob<HighDataFeedBackByWeek>(new CronTrigger("0 0 8 ? * FRI"));

            //每天下午17点提醒JIRA反馈情况(周五提醒本周汇总信息)
            JobManager.AddJob<HighDataFeedBackByWeek>(new CronTrigger("0 0 17 ? * FRI"));


            */

        }

        private static void InitLogSystem()
        {
            LogHelper.Init("机器人日志");

            LogHelper.BindingDiagnosticsDebugLog();

            LogHelper.Debug("日志组件初始化完成");
        }

        private static void InitFile()
        {
            CreateDirectory(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, ConstService.APP_DATA_PATH));

            CreateFile(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, ConstService.APP_DATA_PATH, ConstService.NOMAL_TEXT_MSG_PATH), ConstService.NOMAL_TEXT_MSG_CONTENT);

            CreateFile(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, ConstService.APP_DATA_PATH, ConstService.CST_TEXT_MSG_PATH), ConstService.CST_TEXT_MSG_CONTENT);

            CreateFile(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, ConstService.APP_DATA_PATH, ConstService.JIRA_CONFIG_PATH), ConstService.JIRA_CONFIG_CONTENT);

        }


        public static void Shutdown()

        {
            // 停止所有的定时任务
            IgnoreEx(JobManager.Shutdown);
        }

        public static void IgnoreEx(Action action)
        {
            try
            {
                action();
            }
            catch (Exception ex) /* 忽略错误 */
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
            }
        }

        private static void CreateDirectory(string strPath)
        {
            if (!Directory.Exists(strPath))
            {
                Directory.CreateDirectory(strPath);
            }
        }

        private static void CreateFile(string strPath, string content = "")
        {
            if (!File.Exists(strPath))
            {
                File.AppendAllText(strPath, content);
            }
        }
    }
}
